<template>
  <div class="flex justify-center items-center min-w-full min-h-screen bg-sky-800">
    <div class="relative p-5 pt-24 w-96 bg-white rounded shadow">
      <div class="absolute z-10 top-0 left-1/2 -translate-x-2/4 -translate-y-2/4 p-2 border w-32 h-32 rounded-full bg-white shadow">
        <img class="block w-full h-full bg-gray-200 rounded-full" src="../assets/logo.png" />
      </div>
      <el-form ref="formRef" :model="loginForm" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username">
            <template #prefix>
              <i class="iconfont icon-username" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" show-password>
            <template #prefix>
              <i class="iconfont icon-password" />
            </template>
          </el-input>
        </el-form-item>
        <div class="flex justify-end">
          <el-form-item>
            <el-button type="primary" @click="login(formRef)">登录</el-button>
            <el-button type="info" @click="reset(formRef)">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, inject } from 'vue'
  import { useRouter } from 'vue-router';
  import type { FormInstance, FormItemRule } from 'element-plus'
  import type { AxiosInstance } from 'axios'

  const axios = <AxiosInstance>inject('axios')
  const formRef = ref()
  const router = useRouter()
  const loginForm = reactive({
    username: 'admin',
    password: '123456'
  })
  type rules = {
    username: FormItemRule[],
    password: FormItemRule[]
  }
  const rules = reactive<rules>({
    username: [
      { required: true, message: '请输入登录名称', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入登录密码', trigger: 'blur' },
      { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
    ]
  })

  const login = async (formEl: FormInstance) => {
    const valid = await formEl.validate()
    if (valid) {
      try {
        const res: apiData = await axios.post('login', loginForm)
        console.log(res)
        if (res.meta.status === 200) {
          ElMessage({
            message: '登录成功',
            type: 'success',
          })
          sessionStorage.setItem('token', res.data.token)
          router.push('/home')
        } else {
          ElMessage({
          message: '登录失败 ' + res.meta.msg || '',
          type: 'error'
        })
        }
      } catch(e: any) {
        ElMessage({
          message: '请求失败 ' + e.message || '',
          type: 'error'
        })
      }
    } else {
      console.log('error')
    }
  }
  const reset = (formEl: FormInstance) => {
    formEl.resetFields()
  }
</script>